package com.guanghua.brick.html.export;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.guanghua.brick.html.Constant;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;

public class ExportQueryResultInterceptor implements Interceptor {
	
	private static Log logger = LogFactory.getLog(ExportQueryResultInterceptor.class);

	public void destroy() {}

	public void init() {}
	
	
	//判断是否是需要导出的方法，是的话就返回到默认的导出result
	public String intercept(ActionInvocation action) throws Exception {
		String exportKey = ServletActionContext.getRequest().getParameter(Constant.GLOBE_EXPORT_KEY);
		logger.trace("export key:" + exportKey);
		if (exportKey == null) return action.invoke();
		
		//获取调用的方法
		String m = action.getProxy().getMethod();
		m = (m!=null)?m:"execute";
		Method method = action.getAction().getClass().getMethod(m, (Class[])null);
		logger.trace("export method:" + m);
		
		//export的annotation
		Export e = null;
		if (method != null) e = (Export)method.getAnnotation(Export.class);
		if (e == null) return action.invoke();
		logger.trace("export result name:" + e.resultName());
		
		//获取result name并且执行
		final String resultName = e.resultName();
		action.addPreResultListener(new PreResultListener() {
            public void beforeResult(ActionInvocation invocation, String resultCode) {
            	ExportQueryResultInterceptor.logger.trace("goto export result after action:" + resultName);
            	invocation.setResultCode(resultName);
            }
       });

		return action.invoke();
	}
}
